const cos = require("../utils/cos");
const fs = require("fs");
const path = require("path");

module.exports = function (file) {
  // 获得文件扩展名
  const extName = file.originalname.split(".");
  // 获得文件名
  newFilename = file.filename + "." + extName.pop();
  // 获得文件路径
  filePath = path.join(process.cwd(), "uploads", file.filename);

  // 上传图片
  return new Promise(async (resolve, reject) => {
    let cosResult = await cos.putObject({
      key: "demo/" + newFilename, // 上传路径
      buffer: fs.createReadStream(filePath),
    });
    // 删除暂存的文件
    fs.unlinkSync(filePath);
    // 返回图片路径
    resolve("https://" + cosResult.Location) ;
  });
};
